<!-- src/views/outbound/hhh/LogisticsDialog.vue -->
<script setup>
import { ref } from 'vue';
import { getLogisticsCompanyListApi } from '@/api/logisticsCompany';
import { transportApi } from '@/api/outbound/outboundOrderWeights';
import { ElMessage } from 'element-plus';

// 弹窗控制
const dialogVisible = ref(false);
const title = ref('选择物流公司');

// 物流公司列表
const logisticsCompanies = ref([]);

// 选中的物流公司
const selectedLogistics = ref('');

// 当前行数据
const currentRow = ref(null);

// 提交事件
const emit = defineEmits(['select', 'success']);

// 打开弹窗
const open = (row) => {
  currentRow.value = row;
  selectedLogistics.value = '';
  dialogVisible.value = true;
  fetchLogisticsCompanies();
};

// 关闭弹窗
const close = () => {
  dialogVisible.value = false;
};

// 获取物流公司列表
const fetchLogisticsCompanies = async () => {
  try {
    const res = await getLogisticsCompanyListApi();
    logisticsCompanies.value = res.data;
  } catch (error) {
    ElMessage.error('获取物流公司列表失败');
  }
};

// 确认选择
const handleConfirm = async () => {
  if (!selectedLogistics.value) {
    ElMessage.warning('请选择物流公司');
    return;
  }
  
  try {
    const selectedCompany = logisticsCompanies.value.find(company => company.id == selectedLogistics.value);
    
    // 构造传输对象
    const transportData = {
      id: currentRow.value.id,
      price: selectedCompany.minPrice,
      logisticsCompanyId: selectedCompany.id
    };
    
    // 调用后端接口
    await transportApi(transportData);
    
    ElMessage.success('物流信息设置成功');
    
    emit('select', {
      row: currentRow.value,
      logisticsCompany: selectedCompany
    });
    
    emit('success');
    
    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error('物流信息设置失败');
  }
};

// 暴露方法给外部调用
defineExpose({
  open,
  close
});
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="500px"
  >
    <el-form label-width="100px">
      <el-form-item label="物流公司">
        <el-select 
          v-model="selectedLogistics" 
          placeholder="请选择物流公司" 
          style="width: 100%"
        >
          <el-option
            v-for="company in logisticsCompanies"
            :key="company.id"
            :label="company.companyName"
            :value="company.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="最低价格" v-if="selectedLogistics">
        <el-input 
          :value="logisticsCompanies.find(c => c.id == selectedLogistics)?.minPrice || ''" 
          disabled
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>